<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>crash</title>
</head>
<style>
  canvas {
    display: block;
    border: 1px solid green;
    margin: 30px auto;
  }
</style>
<body>
  <canvas id="canvas" width="600" height="400"></canvas>
</body>
<script>
  const canvas = document.getElementById('canvas')
  const ctx = canvas.getContext('2d');
  const dpr = window.devicePixelRatio || 1

  /** 
   * 获取适应dpr的canvas画布
  */
  function getCanvasWithDpr(dpr, canvas, ctx) {
    const oldWidth = canvas.width
    const oldHeight = canvas.height

    canvas.width = oldWidth * dpr
    canvas.height = oldHeight * dpr

    canvas.style.width = oldWidth + 'px'
    canvas.style.height = oldHeight + 'px'

    ctx.scale(dpr, dpr)
  }

  getCanvasWithDpr(dpr, canvas, ctx)

  const wd = canvas.style.width.replace(/\D/g, '')
  const ht = canvas.style.height.replace(/\D/g, '')
  let x = y = 100, r = 10
  let xSpeed = 5
  let ySpeed = 5

  const drawCircle = (x, y, r) => {
    ctx.beginPath()
    ctx.fillStyle = 'orange'
    ctx.arc(x, y, r, 0, Math.PI * 2)
    ctx.fill()
    ctx.closePath()
  }

  setInterval(() => {
    ctx.clearRect(0, 0, wd, ht) // 清空画布
    if(x - r <= 0 || x + r >= wd) {
      xSpeed = -xSpeed
    }
    if(y - r <= 0 || y + r >= ht) {
      ySpeed = -ySpeed
    }
    x += xSpeed
    y += ySpeed
    drawCircle(x, y, r)
  }, 20)

  drawCircle(x, y, r)


</script>
</html>